#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

const packageJsonPath = path.join(__dirname, 'pkg', 'package.json');
const readmeSrcPath = path.join(__dirname, 'README.md');
const readmeDestPath = path.join(__dirname, 'pkg', 'README.md');
const exampleSrcPath = path.join(__dirname, 'example');
const exampleDestPath = path.join(__dirname, 'pkg', 'example');

function copyDir(src, dest) {
  if (!fs.existsSync(dest)) {
    fs.mkdirSync(dest, { recursive: true });
  }
  
  const items = fs.readdirSync(src);
  
  for (const item of items) {
    if (item === 'node_modules') continue; // 跳过 node_modules 目录
    const srcPath = path.join(src, item);
    const destPath = path.join(dest, item);
    
    if (fs.statSync(srcPath).isDirectory()) {
      copyDir(srcPath, destPath);
    } else {
      fs.copyFileSync(srcPath, destPath);
    }
  }
}

try {
  // 复制 README.md 到 pkg 目录
  if (fs.existsSync(readmeSrcPath)) {
    fs.copyFileSync(readmeSrcPath, readmeDestPath);
    console.log('✓ README.md copied to pkg/');
  } else {
    console.warn('⚠ README.md not found in root directory');
  }

  // 复制 example 目录到 pkg 目录
  if (fs.existsSync(exampleSrcPath)) {
    copyDir(exampleSrcPath, exampleDestPath);
    console.log('✓ example directory copied to pkg/');
  } else {
    console.warn('⚠ example directory not found in root directory');
  }

  // 更新 package.json
  const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));

  // 更新 files 字段，包含所有必要的文件
  if (!packageJson.files.includes('README.md')) {
    packageJson.files.push('README.md');
  }
  
  // 添加 example 目录到 files 字段
  if (!packageJson.files.includes('example')) {
    packageJson.files.push('example');
  }

  // 修复 sideEffects 字段 - 必须为 true，因为 index.js 中有顶层代码初始化 WASM
  packageJson.sideEffects = true;

  // 写回文件
  fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2) + '\n');

  console.log('✓ package.json updated successfully');
  console.log('✓ Added README.md to files');
  console.log('✓ Added example directory to files');
  console.log('✓ Fixed sideEffects to true');
} catch (error) {
  console.error('✗ Error updating package.json:', error.message);
  process.exit(1);
}